﻿/*
Commerce by Onex – eCommerce software platform (www.ecommerce.byonex.com)
Copyright (C) 2008-2010 by Onex Group

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 
 */
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using ShopModel;
using ShopBLL;
/// <summary>
/// Kontrolka do wyszukiwania
/// </summary>
/// <remarks>
/// Autor: Paweł Janiszewski
/// Data: 05.2008
/// Ostantnia modyfikacja: 20.06.2008
/// </remarks>
public partial class ctrlSearchInCategory : System.Web.UI.UserControl
{
    #region CONSTANTS

    private const string PREFIX = "ctrl";

    #endregion CONSTANTS

    #region VARIABLES

    public event ProductSearchEventHandler ButtonSearchClick;
    private bool searchPanelCreated;
    private int categoryId = -1;

    #endregion VARIABLES

    #region PROPERTIES

    public int CategoryId
    {
        set
        {
            categoryId = value;
            ViewState["CategoryId"] = categoryId;
        }
    }

    private List<ProductPropertyDetail> SearchCriteria
    {
        get
        {
            if (Session["SearchCriteria"] == null)
            {
                return new List<ProductPropertyDetail>();
            }
            else
            {
                return (List<ProductPropertyDetail>)Session["SearchCriteria"];
            }
        }

        set
        {
            Session["SearchCriteria"] = value;
        }
    }
    
    #endregion PROPERTIES

    #region METHODS

    public void SetSearchCriteriaValue(ProductSearchCriteria criteria)
    {
        DropDownList ddl;
        TextBox txt;
        ListItem item;

        if (Session["SearchCriteria"] != null)
        {
            if (!searchPanelCreated)
            {
                CreateSearchPanel((List<ProductPropertyDetail>)Session["SearchCriteria"]);
            }

            txtName.Text = criteria.Name;

            if (criteria.PriceFrom > 0)
            {
                txtPriceFrom.Text = decimal.Round(criteria.PriceFrom).ToString();
            }

            if (criteria.PriceTo > 0)
            {
                txtPriceTo.Text = decimal.Round(criteria.PriceTo).ToString();
            }

            cbPromotedOnly.Checked = criteria.PromotedOnly;

            foreach (ProductProperty current in criteria.SearchCriteria)
            {
                if (current.TypeOfProperty == PropertyType.Dictionary)
                {
                    ddl = (DropDownList)tblProperties.FindControl(PREFIX + current.Id.ToString());
                    if (ddl != null)
                    {
                        item = ddl.Items.FindByText(current.Value);
                        if (item != null)
                        {
                            item.Selected = true;
                        }
                    }
                }

                if (current.TypeOfProperty == PropertyType.Text)
                {
                    txt = (TextBox)tblProperties.FindControl(PREFIX + current.Id.ToString());
                    if (txt != null)
                    {
                        txt.Text = current.Value;
                    }
                }

                if (current.TypeOfProperty == PropertyType.Text)
                {
                    TextBox txtFrom = (TextBox)tblProperties.FindControl(PREFIX + current.Id.ToString() + "From");
                    TextBox txtTo = (TextBox)tblProperties.FindControl(PREFIX + current.Id.ToString() + "To");

                    if (txtFrom != null)
                    {
                        txtFrom.Text = current.NumericValueFrom.ToString();
                    }

                    if (txtTo != null)
                    {
                        txtTo.Text = current.NumericValueTo.ToString();
                    }
                }
            }
        }
    }

    protected void CreateSearchPanel(List<ProductPropertyDetail> searchCriteria)
    {
        if (searchCriteria.Count == 0)// jeżli nie ma włąściwości ukrywa Zaawansowane szukanie
        {
            pnlExpandSearchProperty.Visible = false;
            tblProperties.Visible = false;
            cpeSearchControl.Enabled = false;
            return;
        }

        Label lbl;
        TextBox txt;
        DropDownList ddl;
        tblProperties.Rows.Add(new TableRow());
        searchPanelCreated = true;
        int columnCount = 0;
        int rowCount = 0;
        foreach (ProductPropertyDetail current in searchCriteria)
        {
            if (current.TypeOfProperty == PropertyType.Dictionary || current.TypeOfProperty == PropertyType.MultiDictionary)
            {
                lbl = new Label();
                lbl.Text = current.Name + ":";

                ddl = new DropDownList();
                ddl.ID = PREFIX + current.Id.ToString();
                ddl.DataSource = current.ValuesList;
                ddl.DataTextField = "Name";
                ddl.DataValueField = "Value";
                ddl.DataBind();

                ddl.Width = Unit.Pixel(150);
                ddl.Items.Insert(0, new ListItem("", "-1"));

                lbl.AssociatedControlID = ddl.ID;

                tblProperties.Rows[rowCount].Cells.Add(NewCell(lbl, true));
                tblProperties.Rows[rowCount].Cells.Add(NewCell(ddl, false));
            }

            if (current.TypeOfProperty == PropertyType.Text)
            {
                lbl = new Label();
                lbl.Text = current.Name + ":";

                txt = new TextBox();
                txt.ID = PREFIX + current.Id.ToString();
                txt.Width = Unit.Pixel(145);


                lbl.AssociatedControlID = txt.ID;

                tblProperties.Rows[rowCount].Cells.Add(NewCell(lbl, true));
                tblProperties.Rows[rowCount].Cells.Add(NewCell(txt, false));
            }

            if (current.TypeOfProperty == PropertyType.Numeric)
            {
                Label lblFrom = new Label();
                Label lblTo = new Label();
                lblFrom.Text = current.Name + ":";
                lblTo.Text = " - ";

                TextBox txtForm = new TextBox();
                TextBox txtTo = new TextBox();
                txtForm.ID = PREFIX + current.Id.ToString() + "From";
                txtForm.Width = Unit.Pixel(60);

                txtTo.ID = PREFIX + current.Id.ToString() + "To";
                txtTo.Width = Unit.Pixel(60);

                lblFrom.AssociatedControlID = txtForm.ID;
                lblTo.AssociatedControlID = txtTo.ID;

                tblProperties.Rows[rowCount].Cells.Add(NewCell(lblFrom, true));
                tblProperties.Rows[rowCount].Cells.Add(NewCell(txtForm, lblTo, txtTo, false));
            }


            columnCount++;
            if (columnCount == 2)
            {
                columnCount = 0;
                rowCount++;
                tblProperties.Rows.Add(new TableRow());
            }
        }
        
        if (columnCount == 1)
        {
            tblProperties.Rows[rowCount].Cells.Add(new TableCell());
            tblProperties.Rows[rowCount].Cells.Add(new TableCell());
        }


        this.EnsureChildControls();
    }

    private TableCell NewCell(Control ctrl, bool RigthAlign)
    {
        TableCell cell = new TableCell();
        if (RigthAlign) cell.HorizontalAlign = HorizontalAlign.Right;
        cell.Controls.Add(ctrl);
        cell.Width = Unit.Percentage(25);

        return cell;
    }

    private TableCell NewCell(Control ctrl1, Control ctrl2, Control ctrl3, bool RigthAlign)
    {
        TableCell cell = new TableCell();
        if (RigthAlign) cell.HorizontalAlign = HorizontalAlign.Right;
        cell.Controls.Add(ctrl1);
        cell.Controls.Add(ctrl2);
        cell.Controls.Add(ctrl3);
        cell.Width = Unit.Percentage(25);

        return cell;
    }

    #endregion METHODS

    #region EVENTS

    protected void btnSearch_Click(object sender, EventArgs e)
    {
        Control tempControl;
        TextBox txt;
        DropDownList ddl;
        decimal temp;
        bool wrongFormat = false;
        Regex testSqlInjection = new Regex(@"[^\d\w\s.,]");
        ProductSearchCriteria eventArgs = new ProductSearchCriteria();
        eventArgs.CategoryId = categoryId;
        eventArgs.Name = txtName.Text;
        eventArgs.PromotedOnly = cbPromotedOnly.Checked;

        lblWrongFormat.Visible = false;
        lWrongFormatBreakLine.Visible = false;

        if (!decimal.TryParse(txtPriceFrom.Text, out temp))
        {
            eventArgs.PriceFrom = -1;
        }
        else
        {
            eventArgs.PriceFrom = temp;
        }

        if (!decimal.TryParse(txtPriceTo.Text, out temp))
        {
            eventArgs.PriceTo = -1;
        }
        else
        {
            eventArgs.PriceTo = temp;
        }

        List<ProductPropertyDetail> searchCriteria = SearchCriteria;
        List<ProductProperty> searchValue = new List<ProductProperty>();

        foreach (ProductPropertyDetail current in searchCriteria)
        {
            //if (current.IsDictionaryType)
            //{



            if (current.TypeOfProperty == PropertyType.Dictionary || current.TypeOfProperty == PropertyType.MultiDictionary)
            {
                tempControl = tblProperties.FindControl(PREFIX + current.Id.ToString());
                ddl = tempControl as DropDownList;
                if (ddl != null)
                {
                    if (ddl.SelectedValue != "-1")
                    {
                        current.Value = ddl.SelectedItem.Text;
                        searchValue.Add((ProductProperty)current);
                    }
                }
            }


            if (current.TypeOfProperty == PropertyType.Text)
            {
                tempControl = tblProperties.FindControl(PREFIX + current.Id.ToString());
                txt = tempControl as TextBox;
                if (txt != null && !string.IsNullOrEmpty(txt.Text))
                {
                    if (testSqlInjection.IsMatch(txt.Text))
                    {
                        wrongFormat = true;
                        lblWrongFormat.Visible = true;
                        lWrongFormatBreakLine.Visible = true;
                        break;
                    }
                    current.Value = txt.Text;
                    searchValue.Add((ProductProperty)current);
                }
            }

            if (current.TypeOfProperty == PropertyType.Numeric)
            {
                Control tempControlFrom = tblProperties.FindControl(PREFIX + current.Id.ToString() + "From");
                Control tempControlTo = tblProperties.FindControl(PREFIX + current.Id.ToString() + "To");

                TextBox txtFrom = tempControlFrom as TextBox;
                TextBox txtTo = tempControlTo as TextBox;

                decimal tmpFrom = -1;
                decimal tmpTo = -1;

                if (txtFrom != null)
                    decimal.TryParse(txtFrom.Text, out tmpFrom);

                if (txtTo != null)
                    decimal.TryParse(txtTo.Text, out tmpTo);

                if (tmpFrom >= 0 || tmpTo >= 0)
                {
                    current.NumericValueFrom = tmpFrom;
                    current.NumericValueTo = tmpTo;

                    searchValue.Add((ProductProperty)current);
                }
            }
        }

        eventArgs.SearchCriteria = searchValue;

        if (ButtonSearchClick != null && !wrongFormat)
        {
            ButtonSearchClick(eventArgs);
        }
    }
    
    #endregion EVENTS

    #region PAGE EVENTS

    protected void Page_Init(object sender, EventArgs e)
    {
        searchPanelCreated = false;
        if (IsPostBack)
        {
            CreateSearchPanel(SearchCriteria);
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack && ViewState["CategoryId"] != null)
            categoryId = (int)ViewState["CategoryId"];
    }

    protected void Page_PreRender(object sender, EventArgs e)
    {
        if (!IsPostBack && !searchPanelCreated)
        {
            ProductsManager menager = ProductsManager.Instance;
            List<ProductPropertyDetail> searchCriteria = menager.GetSearchCriteria(categoryId, ShopBLL.CommonTools.CurrentLanguageID);
            SearchCriteria = searchCriteria;

            CreateSearchPanel(searchCriteria);
        }
    }
    
    #endregion PAGE EVENTS
}
